package com.yanyeori.framework.redis.util;

import com.yanyeori.framework.core.constant.BaseWebCodeEnum;
import com.yanyeori.framework.core.exception.BusinessException;
import com.yanyeori.framework.core.function.NonFunction;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * redis分布式锁工具类
 *
 * @author chenkuan 2022/11/19
 */
public class RedisLockUtil {

    private final RedissonClient redissonClient;

    public RedisLockUtil(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public void tryLock(String key, NonFunction function, long waitTime, long timeout, TimeUnit unit) {
        Assert.notNull(key, "Key cannot be null");
        Assert.notNull(function, "Function cannot be null");
        RLock lock = redissonClient.getLock(key);
        try {
            if (lock.tryLock(waitTime, timeout, unit)) {
                function.apply();
            } else {
                throw new BusinessException(BaseWebCodeEnum.SERVER_BUSY.code(), BaseWebCodeEnum.SERVER_BUSY.msg());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }

    public <T> T tryLock(String key, Supplier<T> supplier, long waitTime, long timeout, TimeUnit unit) {
        Assert.notNull(key, "Key cannot be null");
        Assert.notNull(supplier, "Supplier cannot be null");
        RLock lock = redissonClient.getLock(key);
        try {
            if (lock.tryLock(waitTime, timeout, unit)) {
                return supplier.get();
            } else {
                throw new BusinessException(BaseWebCodeEnum.SERVER_BUSY.code(), BaseWebCodeEnum.SERVER_BUSY.msg());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
